package 反射5;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MyJbutils {
    //findList("select * from stu",Car.class)
    public static <T> List<T> findList(String sql, Class<T> c) throws Exception {
        //创建集合，存储所有对象数据
        ArrayList<T> arrayList = new ArrayList<>();
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取链接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "123456");
            //创建statement
            Statement statement = conn.createStatement();
            //返回结果集合
            ResultSet resultSet = statement.executeQuery(sql);
            System.out.println("resultSet=" + resultSet);
            //从结果集合中获取结果集的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            System.out.println("metaData=" + metaData);
            //获取集合中列数
            int count = metaData.getColumnCount();
            System.out.println("count=" + count);
            //解析结果集合
            while (resultSet.next()) {
                //动态获取一行数据之后，封装成实体对象
                T t = c.newInstance();
                System.out.println("t=" + t);
                for (int i = 1; i <= count; i++) {
                    //通过列的序号获取列值
                    Object value = resultSet.getObject(i);
                    if (value != null) {
                        //通过列的序号获取列名
                        String columnName = metaData.getColumnName(i);
                        System.out.println("columnName = " + columnName);
                        Field declaredField = c.getDeclaredField(columnName);
                        declaredField.setAccessible(true);//允许访问javabean私有属性
                        declaredField.set(t, value);
                    }
                }
                arrayList.add(t);
            }
        return arrayList;
    }
}






